$(function(){
    $.ajax({ 				  		
			url:baseUrl+'wechat/login/get_jssdk_config',	
			type:'GET',				
			dataType:"json",	
			data:{url:window.location.href},	
	        success:function(data){
	        	if(data.code!=200){	 
				 	$.alert(data.description, "提示");
				}else{
					var js_dk=data.data;
					wxconfig(js_dk.appid.toString(),Number(js_dk.timestamp),js_dk.noncestr.toString(),js_dk.signature.toString())				
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){					
					$.alert(XMLHttpRequest.responseText, "错误");
					
			}
    	});
    	
    	//获取作品
		$('.open_up').on("click",function(e){
			e.stopPropagation();
			var $this=$(this);
			if($this.hasClass("disablebtn")){				
				$.toast("正在上传照片，请稍后...", "text");
			}else{
					
					if($this.attr("disabled")==undefined){	
						$this.attr("disabled",true);
						$("#loadtoast").show();
						//作品页面初始化接口 并且生成作品 得到页面数据
						initializationwork(work_id,function(layout_categoryid){
								opentype=2;		
								$(".workpage").show();				
								$("#originaleditor").show();
								$(".uploadcon").hide();
								lay_listajax();								
								placeImageObj(work_id);
								$this.removeAttr("disabled", "disabled");
								
								
						});
					}
				}
			
			
			
		})
    	
    	//照片像素过低，可能导致照片模糊
		$(document).on('click','.weui-icon-warn',function(e){	
			e.stopPropagation();			
			$.toast("照片像素过低，可能导致照片模糊", "text");
		})
    	
    	//批量上传图片
    	$('.uploadcon').on('touchend','#uploaderInput',function(e){
    		if($(this).hasClass("disablebtn")){				
				$.toast("正在上传照片，请稍后...", "text");
			}else{
				var img_count=$(this).attr("large_image_num");
				if(img_count>0){
					if(img_count>9){
						//$(this).attr("large_image_num",count-9);
						chooseImage(9);
					}else{						
						chooseImage(img_count);
						//$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
					}
				}else{					
					$.toast("最多只能上传"+$(this).attr("image_num")+"张照片", "text");
				}			
			}
		})    	
    	
		
		$(document).on('click','.uploadbox .weui-uploader__file',function(e){
			if($(this).children().hasClass('wx_uprefresh')){				
	    		$(".nextbtn").addClass("disablebtn");
	    		var item=$(this).closest('li');
	    		wxreshresh(item,item.find('.upload_img').attr('src'),item.attr('name'));
			}
    		
    		
		})    	
    	
    //删除图片
	$('.weui-uploader__files').on("click",".delimportimg",function(){
		$(this).closest("li").remove();
	})	
    	
})
//通过config接口注入权限验证配置
function wxconfig(appId,timestamp,nonceStr,signature){
	wx.config({
      debug: false,
      appId: appId,
      timestamp: timestamp,
      nonceStr: nonceStr,
      signature: signature,
      jsApiList: [        
         'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
        'hideMenuItems',
        'showMenuItems',
        'hideOptionMenu',
        'showOptionMenu',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage'	
      ]
  });
	
}

wx.ready(function() {
	// 1 判断当前版本是否支持指定 JS 接口，支持批量判断
	wx.checkJsApi({
		jsApiList: [
		 'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
        'hideMenuItems',
        'showMenuItems',
        'hideOptionMenu',
        'showOptionMenu',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage'
		], // 需要检测的JS接口列表，所有JS接口列表见附录2,
		success: function(res) {
			// 以键值对的形式返回，可用的api值true，不可用为false
			// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
			try{
			wx.hideOptionMenu();//隐藏分享菜单		
		}catch(e){
			//TODO handle the exception
		}
			
			
		
	 }
	});
})
var imageArray=new Array;//临时存储选择的图片

function chooseImage(count){	
	wx.chooseImage({
    count: count, // 默认9
    sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
//      var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		//console.log(res)
		//alert(JSON.stringify(res));		
		imageArray=res.localIds;
		if(res.localIds.length>0){
			/*if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    		getImageData()
	    	}else{
	    	//调用微信的上传接口
 			wx_upload();
	    	}*/
	    	
	    	/* if (window.__wxjs_is_wkwebview){
	    	 	getImageData();
	    	 }else{
	    	 	//调用微信的上传接口*/
 				wx_upload();	
	    	// }
	    	if(!$(".notupload").is(":hidden")){
				$(".notupload").hide();
				$(".nextbtn").addClass("disablebtn").show();
			}
		}
		
		
    }
	
	});
	
}



/*function getImageData(){	
	 var length = imageArray.length;
	if(length > 0){
		var i = 0; 
		var base64onupload = function() {	
		  wx.getLocalImgData({
		      localId: imageArray[i],
		      success: function (res) {
		      	var localData;
		      	 localData  = res.localData.replace('jgp','jpeg');		      	
				 	var data=new Object;
					  data.name=getNowFormatDate();			 
					  data.base64url=localData;
				      data.compress=true;
					 wexingetchange(data,function(){
					 	if(i !=(length-1)){                                  		
	                          i++;
	                          base64onupload();
	                        }else{
	                        imageArray=[];	                       
	                        $(".nextbtn").removeClass("disablebtn");
	                     	}
					 });
			  }
		  });
		
		}
		base64onupload();
	}
	
}*/

// ios 微信上传预览
function getLocalImgurl(imgs,fn){
	var img_url='';
	wx.getLocalImgData({
		localId: imgs,
		success: function (res) {
		   img_url  = res.localData.replace('jgp','jpeg');		
		   fn(img_url);
		}
	});
		
		

}




//调用微信的上传接口
function wx_upload(){
	 var length = imageArray.length;
	if(length > 0){
		
		var i = 0; 		
		var onupload = function() {	
			var localIds = imageArray[i];
			var name= getNowFormatDate();
			var li='<li class="weui-uploader__file weui-uploader__file_status" name="'+name+'">'+
							               	'<div class="upload_img" style="background-image:url('+localIds+')" src="'+localIds+'"></div>'+
							               	'<div class="weui-uploader__file-content la-ball-beat la-sm"><i></i><i></i><i></i> </div>'+
						              	 '</li>';				                
				$("#uploaderFiles").prepend(li);
				
				if (window.__wxjs_is_wkwebview){				
					getLocalImgurl(localIds,function(img_url){
						var item=$('#uploaderFiles li[name="'+name+'"]')
						 item.find(".upload_img").attr('style','background-image:url('+img_url+')');
						 wx_uploadImage(localIds,name);
					});
				}else{
					wx_uploadImage(localIds,name);
				}
				
			
		 	
		}
		
		var wx_uploadImage=function(localIds,name){
				wx.uploadImage({
			 	localId: localIds,
			 	isShowProgressTips: 0,
			 	success: function(res) {		 			 
			 			if(i < length) {		 				
			 				var  obj={
			 					user_id: user_id,
			 					media_id: res.serverId,		 					
			 					work_id: work_id
			 					}
			 				$.ajax({ 			  		
								url:baseUrl+'other/image/upload_image2',	
								type:'POST',
								dataType:"json",		
								data:obj,		
						        success:function(data){
						        	var result=data;
						        	if(result.code!=200){ 
										 $.alert(data.description, "提示");
										 if(!$("#loadtoast").is(":hidden")){
										 	$("#loadtoast").hide();
										 }
										 var item=$('#uploaderFiles li[name="'+name+'"]')
										item.find(".la-ball-beat").remove();
										item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
										
										 
									}else{
										var item=$('#uploaderFiles li[name="'+name+'"]');
										item.addClass("upload_sucess");
										item.find(".la-ball-beat").remove();					
										if(result.data.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
											item.append('<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>');
											console.log('quality' +result.data.quality);
										}							
										item.append('<div class="delimportimg"><i class="weui-icon-cancel"></i></div>');	
										item.removeClass("weui-uploader__file_status");
										$(".upload_num").text($(".upload_sucess").length);									
										$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
										
									}
									if(i !=(length-1)){                                  		
				                         i++;
				                         onupload();
				                    }else{
				                        	
				                     imageArray=[];
				                   $(".nextbtn").removeClass("disablebtn");
				                        
				                    }
								},
								error: function(XMLHttpRequest, textStatus, errorThrown){	
										if(XMLHttpRequest.status==0){										
											 $.alert('加载失败，请重新加载！', "提示");
											 if(!$("#loadtoast").is(":hidden")){
										 	$("#loadtoast").hide();
											 }
										}else{											
											$.alert(XMLHttpRequest.status,"提示");
										}
										var item=$('#uploaderFiles li[name="'+name+'"]')
										item.find(".la-ball-beat").remove();
										item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
													
								}
						  });
			 				
			 				
			 			}
			 		},fail: function (res) {
	                    var item=$('#uploaderFiles li[name="'+name+'"]')
						item.find(".la-ball-beat").remove();
						item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
										
						if(i !=(length-1)){
		                     i++;
		                     onupload();
		                }else{
		                      imageArray=[];
		                     $(".nextbtn").removeClass("disablebtn");	                        
		                 }
	                }
			 	});
		}
		
		
		onupload();
	}
	
	
	
}


//微信上传
function wx_uploadImage(localIds,name){
	
	
	
}









//微信上传失败重新上传
function wxreshresh(element,localIds,name){
	element.find(".up_refresh").remove();
	element.find(".up_refreshtxt").remove();
	element.append('<div class="weui-uploader__file-content la-ball-beat la-sm"><i></i><i></i><i></i> </div>');
	wx.uploadImage({
		 	localId: localIds,
		 	isShowProgressTips: 0,
		 	success: function(res) {		 			 
		 			$.ajax({ 			  		
							url:baseUrl+'other/image/upload_image2',	
							type:'POST',
							dataType:"json",		
							data:{user_id: user_id,	media_id: res.serverId,work_id: work_id},		
					        success:function(result){
					        	var item=$('#uploaderFiles li[name="'+name+'"]');
					        	if(result.code!=200){ 
									 $.alert(result.description, "提示");
									 if(!$("#loadtoast").is(":hidden")){
									 	$("#loadtoast").hide();
									 }
									 
									item.find(".la-ball-beat").remove();
									item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
									
								}else{							
								item.addClass("upload_sucess");
								item.find(".la-ball-beat").remove();					
								if(result.data.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
									item.append('<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>');
									console.log('quality' +result.data.quality);
								}							
								item.append('<div class="delimportimg"><i class="weui-icon-cancel"></i></div>');	
								item.removeClass("weui-uploader__file_status");
								$(".upload_num").text($(".upload_sucess").length);							
								$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
								
		                        $(".nextbtn").removeClass("disablebtn");
			 				}
		 				},
						error: function(XMLHttpRequest, textStatus, errorThrown){	
									if(XMLHttpRequest.status==0){										
										 $.alert('加载失败，请重新加载！', "提示");
										 if(!$("#loadtoast").is(":hidden")){
									 	$("#loadtoast").hide();
										 }
									}else{											
										$.alert(XMLHttpRequest.status,"提示");
									}
									var item=$('#uploaderFiles li[name="'+name+'"]')
									item.find(".la-ball-beat").remove();
									item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
												
						}
					})
		 				
		 		},fail: function (res) {
                    var item=$('#uploaderFiles li[name="'+name+'"]')
					item.find(".la-ball-beat").remove();
					item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
									
					$(".nextbtn").removeClass("disablebtn");
	                 
                }
		 	});
	
}
